package top.byfree.jbyan.saber.bean.dto

import cn.dev33.satoken.stp.StpUtil
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Pattern
import jakarta.validation.constraints.Size
import top.byfree.jbyan.saber.bean.IS_DELETE_NO
import top.byfree.jbyan.saber.bean.Operate
import top.byfree.jbyan.saber.bean.PERM_STATUS_NORMAL
import top.byfree.jbyan.saber.bean.pojo.Perm
import top.byfree.jbyan.saber.bean.vo.UserVo
import top.byfree.jbyan.saber.common.AddGroup
import top.byfree.jbyan.saber.common.UpdateGroup
import java.time.LocalDateTime

/**
 * 权限Dto
 *
 * @author jbyan
 * @since 28/3/2024
 */
data class PermDto(
    /* 权限标识 */
    @field:NotBlank(message = "权限标识不能为空", groups = [AddGroup::class])
    @field:Pattern(
        regexp = "^[0-9_a-zA-Z]+\$",
        message = "权限标识只能包含字母数字和下划线",
        groups = [AddGroup::class, UpdateGroup::class]
    )
    var permKey: String?,

    /* 权限名称 */
    @field:NotBlank(message = "权限名称不能为空", groups = [AddGroup::class])
    @field:Size(
        min = 2,
        max = 8,
        message = "权限名称需要在2-8个字符之间",
        groups = [AddGroup::class, UpdateGroup::class]
    )
    var permName: String?,


    /* 权限状态 */
    @field:Pattern(
        regexp = "^([01])\$",
        message = "权限状态不符合码值规则",
        groups = [AddGroup::class, UpdateGroup::class]
    )
    var status: Int?,
) {
    fun toPerm(cPermId: String, type: Operate): Perm {
        val userVo = (StpUtil.getSession().get("user") as? UserVo)!!
        val perm = Perm {
            permId = cPermId
            gmtModify = LocalDateTime.now()
            modifyBy = userVo.userId
        }

        permName?.let {
            perm.permName = it
        }
        permKey?.let {
            perm.permKey = it
        }

        perm.status = status ?: PERM_STATUS_NORMAL

        if (type == Operate.OPERATE_ADD) {
            perm.gmtCreate = LocalDateTime.now()
            perm.createBy = userVo.userId
            perm.isDelete = IS_DELETE_NO
        }
        return perm
    }
}